<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>DOM操作之新增表数据</title>
        <style>
            #form1{
                display: none;
            }
        </style>
    </head>
    <body>
        <h3>学生餐卡管理</h3>
        <hr>
        <button type="button" onclick="addCard()">开卡</button>
        <form action="" id="form1" onsubmit="return valifrom()">
            <div>
                <label for="">卡号</label>
                <!-- disabled="true"输入框禁止修改 -->
                <input type="text" name="cardnum" disabled="true">
            </div>
            <div>
                <label for="">金额</label>
                <input type="number" name="money">
                
            </div>
            <div>
                <button>提交</button>
                <button type="button" onclick="form1.style='display:none'">取消</button>
            </div>
            <hr>
        </form>
        <table border="1" width="50%" align="center" cellspacing="0" cellpadding="10">
            <thead>
                <th>卡号</th>
                <th>金额</th>
                <th>最后交易时间</th>
            </thead>
            <tbody id="tbody"></tbody>
        </table>
        <script>
            // script 标签中的程序在页面加载完成后自动执行
            let form = document.getElementById("form1");
            let tbody = document.getElementById("tbody");
            let lastcard_num = 10001;
            function addCard(){
                // 让form表单域显示
                form.style="display:block;";
                form.cardnum.value=lastcard_num;
            }
            function valifrom(){
                if(!/\d{2,}/.test(form.money.value)){
                    alert("金额不能低于两位数字！");
                    return false;
                }
                // 将表单数据提取出来，生成tbody中的一行数据
                let tr = document.createElement("tr");
                let td1 = document.createElement("td"); // 卡号
                let td2 = document.createElement("td"); // 金额
                let td3 = document.createElement("td"); // 交易时间

                td1.innerText = lastcard_num;
                td2.innerText = form.money.value;

                let current_data = new Date();
                td3.innerText = current_data.getFullYear()+"-"+(current_data.getMonth()+1)+"-"+current_data.getDate()+" "+current_data.getHours()+":"+current_data.getMinutes()+":"+current_data.getSeconds();

                tr.append(td1,td2,td3);
                tbody.append(tr);
                lastcard_num++;

                // 隐藏
                form.style="display:none";

                // 清空表单数据
                form.reset();
                alert("开卡成功！");
                return false;

            }
        </script>
    </body>
</html>